package com.chinaums.study.restful.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.asynchttpclient.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Service
public class RestfulService {

    private static final String HOST = "172.16.208.86";

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private final AsyncHttpClient httpClient;

    public RestfulService() {
        final AsyncHttpClientConfig config = new DefaultAsyncHttpClientConfig.Builder()
                .setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36")
                .build();
        httpClient = new DefaultAsyncHttpClient(config);
    }

    public CompletableFuture<Map<?, ?>> compare(String fileName1, String fileName2) throws IOException {
        final Map<String, String> params = new HashMap<>();
        params.put("ServiceCode", "face");
        params.put("ServiceScene", "01");
        params.put("TranDate", LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        params.put("TranTime", LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS")));
//        params.put("IdentCardNo", "?");
        params.put("ImgAcsTp", "1");
        params.put("PhotoTp", "1");
        params.put("CnlInd", "3");
        params.put("CmprMode", "1");
        params.put("TmplFlag", "0");
        params.put("FileNmN", fileName1);
        params.put("FileNm2", fileName2);
        params.put("PckgFlag", "0");
        final ObjectMapper objectMapper = new ObjectMapper();
        final BoundRequestBuilder requestBuilder = httpClient.preparePost(getUrl(8080, "face-service/"))
                .setBody(objectMapper.writeValueAsBytes(params));
        return requestBuilder.execute(new AsyncCompletionHandler<Map<?, ?>>() {
            @Override
            public Map<?, ?> onCompleted(final Response response) throws Exception {
                return objectMapper.readValue(response.getResponseBody(StandardCharsets.UTF_8), Map.class);
            }
        }).toCompletableFuture();
    }

    private String getUrl(final int port, final String requestPath) {
        return "http://" + HOST + ":" + port + "/" + requestPath;
    }

}
